<template>
    <div class="assembly-storage-page">
        <!-- 顶部信息栏 -->
        <el-form :model="form" inline label-width="100px" class="top-form">
            <el-form-item label="单据日期">
                <el-date-picker v-model="form.billDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期"
                    style="width: 120px" />
            </el-form-item>
            
            <el-form-item label="业务员">
                <el-select v-model="form.salesman" placeholder="(空)" style="width: 100px">
                    <el-option label="业务员1" value="sales1" />
                    <el-option label="业务员2" value="sales2" />
                </el-select>
            </el-form-item>
        </el-form>

        <!-- 功能按钮栏 -->
        <div class="btn-group" style="margin: 8px 0">
            <el-button type="text" @click="handleColumnSetting">列设置</el-button>
            <el-switch v-model="scanMode" active-text="扫描录入" inactive-text="普通录入" />
            <el-button type="text" @click="handleSelectTemplate">选择模板</el-button>
            <el-button type="text" @click="handleSaveAsTemplate">存为模板</el-button>
            <el-button type="text" @click="handleUpdateTemplate">更新模板</el-button>
        </div>

        <!-- 组合件表格 -->
        <div class="table-group" style="margin-top: 12px">
            <div class="group-info">
                <span>组合件：</span>
                <el-input v-model="form.templateCode" placeholder="模板编号" style="width: 100px; margin-right: 12px" />
                <el-input v-model="form.templateName" placeholder="模板名称" style="width: 120px" />
            </div>
            <el-table :data="groupTableData" border style="width: 100%; margin-top: 8px"
                :header-cell-style="{ background: '#F9F9F9' }">
                <el-table-column label="*商品" width="250">
                    <template #default="scope">
                        <el-input v-model="scope.row.goodsName" placeholder="输入商品" clearable
                            style="width: 160px; margin-right: 4px" />
                        <el-button type="text" @click="openGoodsSelect(scope.row)">选择</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="goodsCategory" label="商品类别" width="100" />
                <el-table-column prop="brand" label="品牌" width="80" />
                <el-table-column prop="attribute" label="属性" width="80" />
                <el-table-column prop="unit" label="单位" width="60" />
                <el-table-column prop="warehouse" label="*仓库" width="180">
                    <template #default="scope">
                        <el-select v-model="scope.row.warehouse" placeholder="选择">
                            <el-option label="主仓" value="main" />
                            <el-option label="副仓" value="sub" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="availableStock" label="可用库存" width="100" />
                <el-table-column prop="quantity" label="*数量" width="80">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.quantity" placeholder="输入" clearable />
                    </template>
                </el-table-column>
                <el-table-column prop="inUnitCost" label="入库单位成本" width="120" />
                <el-table-column prop="inCost" label="入库成本" width="100">
                    <template #default="scope">
                        <span>{{ (scope.row.quantity * scope.row.inUnitCost).toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="120" />
            </el-table>
        </div>

        <!-- 子件表格（显示/隐藏控制 + 增删行） -->
        <div class="table-group" style="margin-top: 12px">
            <el-button type="text" @click="toggleSubTable">{{ subTableVisible ? '隐藏子件' : '显示子件' }}</el-button>
            <el-table v-show="subTableVisible" :data="subTableData" border style="width: 100%; margin-top: 8px"
                :header-cell-style="{ background: '#F9F9F9' }">
                <el-table-column label="*商品" width="250">
                    <template #default="scope">
                        <el-input v-model="scope.row.goodsName" placeholder="输入商品" clearable
                            style="width: 160px; margin-right: 4px" />
                        <el-button type="text" @click="openGoodsSelect(scope.row)">选择</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="brand" label="品牌" width="80" />
                <el-table-column prop="attribute" label="属性" width="80" />
                <el-table-column prop="unit" label="单位" width="60" />
                <el-table-column prop="warehouse" label="*仓库" width="180">
                    <template #default="scope">
                        <el-select v-model="scope.row.warehouse" placeholder="选择">
                            <el-option label="主仓" value="main" />
                            <el-option label="副仓" value="sub" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="batch" label="批量" width="60" />
                <el-table-column prop="availableStock" label="可用库存" width="180" />
                <el-table-column prop="quantity" label="*数量" width="80">
                    <template #default="scope">
                        <el-input v-model.number="scope.row.quantity" placeholder="输入" clearable />
                    </template>
                </el-table-column>
                <el-table-column prop="outUnitCost" label="出库单位成本" width="120" />
                <el-table-column prop="outCost" label="出库成本" width="100">
                    <template #default="scope">
                        <span>{{ (scope.row.quantity * scope.row.outUnitCost).toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <!-- 子件表格操作列（增删行） -->
                <el-table-column label="操作" width="80" align="center">
                    <template #default="scope">
                        <el-button type="text" icon="el-icon-plus" @click="addSubRow(scope.$index)">添加</el-button>
                        <el-button type="text" icon="el-icon-delete" @click="deleteSubRow(scope.$index)"
                            v-if="scope.$index > 0">减少</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="120" />
            </el-table>
            <el-table :data="summaryData" border style="width: 100%" :header-cell-style="{ background: '#FDE9CC' }">
                <el-table-column label="合计：" width="80" />
                <el-table-column label="入库成本合计" width="120">
                    <template #default>
                        <span>{{ totalInCost.toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="出库成本合计" width="120">
                    <template #default>
                        <span>{{ totalOutCost.toFixed(2) }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 合计栏 -->
        <div class="summary-bar" style="margin-top: 12px">
          
            <el-form-item label="拆卸费用">
                <el-input v-model="form.assemblyCost" placeholder="0.00" style="width: 100px" />
            </el-form-item>
        </div>

        <!-- 商品选择弹窗 -->
        <el-dialog title="选择商品" v-model="goodsSelectVisible" width="700px" @close="handleGoodsSelectClose">
            <el-input v-model="goodsSearchKey" placeholder="输入商品编号/名称" clearable
                style="width: 240px; margin-bottom: 8px" @keyup.enter="searchGoods" />
            <el-table :data="goodsList" border style="width: 100%; max-height: 300px; overflow-y: auto"
                @selection-change="handleGoodsSelection">
                <el-table-column type="selection" width="50" />
                <el-table-column prop="goodsCode" label="商品编号" width="120" />
                <el-table-column prop="goodsName" label="商品名称" width="200" />
                <el-table-column prop="spec" label="规格" width="150" />
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="goodsSelectVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmGoodsSelect">确认选择</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElDialog, ElInput, ElButton, ElTable, ElTableColumn, ElSelect, ElOption, ElSwitch } from 'element-plus';

export default {
    name: 'DismantlingSheet',
    components: { ElDialog, ElInput, ElButton, ElTable, ElTableColumn, ElSelect, ElOption, ElSwitch },
    setup() {
        // 表单数据
        const form = reactive({
            billDate: '2025-06-25',
            assemblyCost: '0.00',
            salesman: '',
            templateCode: '',
            templateName: '',
        });

        // 组合件表格数据
        const groupTableData = reactive([
            {
                goodsName: '',
                goodsCategory: '',
                brand: '',
                attribute: '',
                unit: '',
                warehouse: '',
                availableStock: '',
                quantity: 0,
                inUnitCost: 0,
                inCost: 0,
                remark: '',
            },
        ]);

        // 子件表格数据（默认隐藏）
        const subTableVisible = ref(false);
        const subTableData = reactive([
            {
                goodsName: '',
                brand: '',
                attribute: '',
                unit: '',
                warehouse: '',
                batch: '',
                availableStock: '',
                quantity: 0,
                outUnitCost: 0,
                outCost: 0,
                remark: '',
            },
        ]);

        // 商品选择弹窗相关
        const goodsSelectVisible = ref(false);
        const currentRow = ref(null);
        const goodsSearchKey = ref('');
        const goodsList = reactive([
            { goodsCode: 'SP001', goodsName: '商品A', spec: '规格1' },
            { goodsCode: 'SP002', goodsName: '商品B', spec: '规格2' },
        ]);
        const selectedGoods = ref([]);

        // 计算属性
        const totalInCost = computed(() => {
            return groupTableData.reduce((sum, item) => sum + item.quantity * item.inUnitCost, 0);
        });
        const totalOutCost = computed(() => {
            return subTableData.reduce((sum, item) => sum + item.quantity * item.outUnitCost, 0);
        });

        // 方法定义：功能按钮
        const handleColumnSetting = () => ElMessage.info('列设置功能待实现');
        const handleSelectTemplate = () => ElMessage.info('选择模板功能待实现');
        const handleSaveAsTemplate = () => ElMessage.info('存为模板功能待实现');
        const handleUpdateTemplate = () => ElMessage.info('更新模板功能待实现');

        // 方法定义：商品选择弹窗
        const openGoodsSelect = (row) => {
            currentRow.value = row;
            goodsSelectVisible.value = true;
        };

        const searchGoods = () => {
            const timeout = setTimeout(() => {
                goodsList.length = 0;
                const mockData = [
                    { goodsCode: 'SP001', goodsName: '商品A', spec: '规格1' },
                    { goodsCode: 'SP002', goodsName: '商品B', spec: '规格2' },
                    { goodsCode: 'SP003', goodsName: '商品C', spec: '规格3' },
                ].filter(item => item.goodsName.includes(goodsSearchKey.value));
                mockData.forEach(item => goodsList.push(item));
            }, 300);
            return () => clearTimeout(timeout);
        };

        const handleGoodsSelection = (selection) => (selectedGoods.value = selection);

        const confirmGoodsSelect = () => {
            if (selectedGoods.value.length && currentRow.value) {
                currentRow.value.goodsName = selectedGoods.value[0].goodsName;
                goodsSelectVisible.value = false;
            } else {
                ElMessage.warning('请选择商品');
            }
        };

        const handleGoodsSelectClose = () => {
            currentRow.value = null;
            goodsSearchKey.value = '';
            selectedGoods.value = [];
            goodsList.length = 0;
            [
                { goodsCode: 'SP001', goodsName: '商品A', spec: '规格1' },
                { goodsCode: 'SP002', goodsName: '商品B', spec: '规格2' },
            ].forEach(item => goodsList.push(item));
        };

        // 方法定义：子件表格显隐
        const toggleSubTable = () => (subTableVisible.value = !subTableVisible.value);

        // 方法定义：子件表格增删行
        const addSubRow = (index) => {
            subTableData.splice(index + 1, 0, {
                goodsName: '',
                brand: '',
                attribute: '',
                unit: '',
                warehouse: '',
                batch: '',
                availableStock: '',
                quantity: 0,
                outUnitCost: 0,
                outCost: 0,
                remark: '',
            });
        };

        const deleteSubRow = (index) => {
            if (index === 0) {
                ElMessage.warning('首行不可删除');
                return;
            }
            subTableData.splice(index, 1);
        };

        return {
            form,
            scanMode: ref(false),
            groupTableData,
            subTableVisible,
            subTableData,
            totalInCost,
            totalOutCost,
            goodsSelectVisible,
            goodsSearchKey,
            goodsList,
            selectedGoods,
            handleColumnSetting,
            handleSelectTemplate,
            handleSaveAsTemplate,
            handleUpdateTemplate,
            openGoodsSelect,
            searchGoods,
            handleGoodsSelection,
            confirmGoodsSelect,
            handleGoodsSelectClose,
            toggleSubTable,
            addSubRow,
            deleteSubRow,
        };
    },
};
</script>

<style scoped>
.assembly-storage-page {
    padding: 24px;
    background: #fff;
    height: 800px;
}

.top-form {
    margin-bottom: 8px;
}

.btn-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.group-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 4px;
}

.table-group {
    margin-top: 16px;
}

.summary-bar {
    margin-top: 16px;
}

.el-dialog__body {
    padding: 16px;
}

/* 滚动条优化 */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}
::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}
::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>